package cn.com.pansky.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class ImageBinaryUtil {
	
	static BASE64Encoder encoder = new sun.misc.BASE64Encoder();      
    static BASE64Decoder decoder = new sun.misc.BASE64Decoder();      
    
    /**
     * 将图片转为16进制
     * @param path
     * @return
     * @throws IOException 
     */
    public static String getImageBinary(String path){
    	File f = new File(path);
		try {
			BufferedImage bi = ImageIO.read(f);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(bi, "jpg", baos);      
			byte[] bytes = baos.toByteArray();
			String str = ImageBinaryUtil.bytesToHexString(bytes);
			return str;
		} catch (IOException e) {
			e.printStackTrace();
		}   
		return null;
    } 
    
  
    /* 
     * 实现字节数组向十六进制的转换
     * 
     */  
    public static String bytesToHexString(byte[] src)  
    {  
        StringBuilder stringBuilder = new StringBuilder("");  
        if (src == null || src.length <= 0)  
        {  
            return null;  
        }  
        for (int i = 0; i < src.length; i++)  
        {  
            int v = src[i] & 0xFF;  
            String hv = Integer.toHexString(v);  
            if (hv.length() < 2)  
            {  
                stringBuilder.append(0);  
            }  
            stringBuilder.append(hv);  
        }  
        return stringBuilder.toString();  
    }  
    
    public static void main(String[] args) throws IOException {
    	String path = "G:/1.jpg";
    	File f = new File(path);
        BufferedImage bi = ImageIO.read(f);    
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bi, "jpg", baos);      
        byte[] bytes = baos.toByteArray();
        String str = ImageBinaryUtil.bytesToHexString(bytes);
    	System.out.println(str);
	}

}
